package com.fingard.dsp.bank.directbank.jxb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 嘉兴银行明细查询
 * Created by F on 2019/08/07
 */
public class JXB01Transaction extends JXB01Base implements ITransaction {
    /**
     * 历史明细
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try{
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //======拼接报文======
                //拼接请求报文体
                JXB01Header header = new JXB01Header();
                header.trsCode="B2EActTrsQry";
                XmlTextWriter xmlReq = new XmlTextWriter();
                writeReqHeader(xmlReq,header);
                xmlReq.writeEndElement();
                xmlReq.writeStartElement("Body");
                xmlReq.writeStartElement("List");
                xmlReq.writeStartElement("Map");
                xmlReq.writeElementString("AcNo",p_req7516.actNum);//账号
                xmlReq.writeElementString("BeginDate",Format.Date8Format.format(tmpCalendarFrom.getTime()));//查询开始日期
                xmlReq.writeElementString("EndDate",Format.Date8Format.format(tmpClndrStepTo.getTime()));//查询结束日期
                xmlReq.writeEndDocument();
                //======拼接报文======
                //发送请求报文
                String[] resutlt = sendToBank(xmlReq.toXmlString(),header.trsCode);
                //处理响应报文
                if(resutlt[0].length()==0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1], tmpSbMsg);
                        if(tmpBkReader!=null) {
                            String respCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                            String respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                            if ("000000".equals(respCode)) {//交易成功
                                while (tmpBkReader.read("/Message/Body/List/Map")){
                                    if("000000".equals(tmpBkReader.readedXElement.getSingleTextNotNull("ReturnCode"))
                                            && p_req7516.actNum.equals(tmpBkReader.readedXElement.getSingleTextNotNull("AcNo"))){
                                        List<XElement> xElementList=tmpBkReader.readedXElement.getSingleChild("List").getChildList("Map");
                                        if(xElementList!=null && xElementList.size()>0){
                                            for(XElement readXElement:xElementList){
                                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                                detail.actArea=p_req7516.actArea;
                                                detail.actNum = p_req7516.actNum;
                                                detail.tranDate =DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("TransDate"));//交易日
                                                detail.valueDate = detail.tranDate;//起息日
                                                detail.tranTime = detail.valueDate+ " 00:00:00";
                                                detail.cur = getBankConfig().getMapKeyByValue("curActMapping",p_req7516.actNum);//币种
                                                detail.accBal = readXElement.getSingleTextNotNull("Balance");//账户余额
                                                String note = readXElement.getSingleTextNotNull("Remark");//摘要
                                                detail.usage = note;
                                                detail.abstr = pickupAbstr(note);//对账码
                                                detail.originator = "";//银行流水号
                                                detail.recAccNum = readXElement.getSingleTextNotNull("PartnerAcct");//对方账号
                                                detail.recAccName = readXElement.getSingleTextNotNull("PartnerAcName");//对方账户名称
                                                detail.recAccBank = "";
                                                String cdFlag=readXElement.getSingleTextNotNull("DCFlag");//借贷标识
                                                String tranAmt=readXElement.getSingleTextNotNull("Amount");//交易额
                                                if("D".equals(cdFlag)){
                                                    if(tranAmt.substring(0,1).equals("-")){
                                                        detail.cdFlag="2";
                                                        detail.tranAmt=tranAmt.substring(1);
                                                    }else {
                                                        detail.cdFlag="1";
                                                        detail.tranAmt=tranAmt;
                                                    }
                                                }else if("C".equals(cdFlag)){
                                                    if(tranAmt.substring(0,1).equals("-")){
                                                        detail.cdFlag="1";
                                                        detail.tranAmt=tranAmt.substring(1);
                                                    }else {
                                                        detail.cdFlag="2";
                                                        detail.tranAmt=tranAmt;
                                                    }
                                                }
                                                detail.comment = "";
                                                retAtsTrans.writeRetDetail(detail);
                                            }
                                        }else {
                                            WriteBankLogLn("交易为空");
                                        }
                                    }else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpBkReader.readedXElement.getSingleTextNotNull("ReturnMsg");
                                        break;
                                    }
                                }
                            }else {//查询异常
                                tmpRespCode = "-1";
                                tmpRespInfo = respInfo;
                                break;
                            }
                        }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:"+ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if(retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
